<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                :page.sync="page"
                :data="tableData"
                :permission="permissionList"
                :table-loading="tableLoading"
                :option="tableOption"
                @on-load="getList"
                @search-change="searchChange"
                @refresh-change="refreshChange"
                @size-change="sizeChange"
                @current-change="currentChange"
                @row-update="handleUpdate"
                @row-save="handleSave"
                @row-del="rowDel">
                <template slot="menuLeft">
                    <el-button
                    icon="el-icon-circle-plus"
                    size="small"
                    type="primary"
                    @click="openform">新增盘点</el-button>
                </template>
                <template slot="status1" slot-scope="scope">
                    <el-switch
                        :value="scope.row.status == '0'? false : true"
                        active-color="#13ce66"
                        @change="changeStatus($event, scope)"
                        inactive-color="#ff4949">
                    </el-switch>
                </template>
                <template slot="menu" slot-scope="scope">
                    <el-button type="text"
                    size="small"
                    @click="openform(scope, '1')">详情</el-button>
                    <el-button type="text"
                    size="small"
                    @click="assignDia(scope)">分配用户</el-button>
                    <!-- <el-button type="text"
                    size="small"
                    @click="submit(scope)">提交盘点结果</el-button> -->
                    <el-button type="text"
                    size="small"
                    @click="showRecord(scope)">盘点记录</el-button>
                </template>
            </avue-crud>
        </basic-container>
         <el-dialog
            :title="title"
            class="asset-dialog"
            v-if="modal"
            :visible.sync="modal"
            @close="closeDialog1"
            :close-on-click-modal="false"
            top="5vh"
            width="800">
            <div class="content">
                <el-form :model="assetData" ref="assetData" :rules="rules" label-width="100px">
                     <el-row>
                        <el-col :span="24">
                            <el-form-item label="盘点单名称" prop="name">
                                <el-input v-model="assetData.name" :disabled="viewFlag" :maxlength="24"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="分配用户" prop="member">
                                <el-select v-model="assetData.member"
                                        placeholder="请选择分配用户"
                                         :disabled="viewFlag"
                                         multiple
                                        clearable>
                                    <el-option v-for="item in optionsYh"
                                            :key="item.userId"
                                            :label="item.realname"
                                            :value="item.userId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="备注">
                                <el-input v-model="assetData.remark"  :disabled="viewFlag" type="textarea"  :maxlength="256" :rows="5"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="wbxx-block">
                <div class="block-header">
                    盘点范围
                </div>
                <el-form :model="assetData" label-width="100px">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="购入日期" prop="supplier">
                                <el-date-picker
                                    v-model="daterange"
                                     :disabled="viewFlag"
                                    type="daterange"
                                    value-format="yyyy-MM-dd"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="截止日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="部门">
                                <avue-input-tree
                                    v-model="assetData.deptIds"
                                     :disabled="viewFlag"
                                    multiple
                                    clearable
                                    :dic="treeDeptData"
                                    :props="defaultProps"
                                    placeholder="请选择所属部门"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="资产分类">
                                <avue-input-tree
                                    v-model="assetData.categoryIds"
                                     :disabled="viewFlag"
                                    multiple
                                    clearable
                                    :dic="treeCateData"
                                    :props="defaultProps"
                                    placeholder="请选择资产分类"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="区域">
                                <avue-input-tree
                                    v-model="assetData.areaIds"
                                     :disabled="viewFlag"
                                    multiple
                                    clearable
                                    :dic="treeData1"
                                    :props="defaultProps"
                                    placeholder="请选择区域"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="管理员">
                                <el-select v-model="assetData.handleIds"
                                        placeholder="请选择管理员"
                                         :disabled="viewFlag"
                                         multiple
                                        clearable>
                                    <el-option v-for="item in optionsGly"
                                            :key="item.userId"
                                            :label="item.realname"
                                            :value="item.userId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="资产状态">
                                <el-select v-model="assetData.assetStatus"
                                        placeholder="请选择资产状态"
                                         :disabled="viewFlag"
                                         multiple
                                        clearable>
                                    <el-option v-for="item in optionsZt"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer" v-if="!viewFlag">
                <el-button @click="closeDialog1">取 消</el-button>
                <el-button type="primary" @click="alarmHandle('assetData')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            title="分配用户"
            class="asset-member-dialog"
            v-if="modal1"
            :visible.sync="modal1"
            @close="closeDialog1"
            :close-on-click-modal="false"
            top="30vh"
            width="30%">
            <div class="content">
                <el-form :model="assetData1" ref="assetData1" :rules="rules" label-width="100px">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="分配用户" prop="member">
                                <el-select v-model="assetData1.member"
                                        placeholder="请选择分配用户"
                                         multiple
                                        clearable>
                                    <el-option v-for="item in optionsYh"
                                            :key="item.userId"
                                            :label="item.realname"
                                            :value="item.userId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog2">取 消</el-button>
                <el-button type="primary" @click="alarmHandle1('assetData1')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :visible.sync="modal2"
            v-if="modal2"
            title="盘点记录"
            fullscreen
            class="pd-dialog"
            :close-on-click-modal="false"
            append-to-body>
            <inventory-record :inventoryId="inventoryId"></inventory-record>
        </el-dialog>
    </div>
</template>

<script>
    import {fetchList, assignMember, addObj, putObj, delObj, changeStatus, submit} from '@/api/asset/assetinventory'
    import {tableOption} from '@/const/crud/asset/assetinventory'
    import {fetchTree} from '@/api/admin/dept'
    import { remote } from "@/api/admin/dict"
    import inventoryRecord from '@/views/asset/assetinventoryrecord/index'
    import { fetchTree as fetchTree1 } from '@/api/asset/assetcategory'
    import { fetchTree as fetchTree2 } from '@/api/admin/sysarea'
    import { roleCodeArray } from "@/api/admin/user"
    import {mapGetters} from 'vuex'

    export default {
        components: { inventoryRecord },
        name: 'assetinventory',
        data() {
            return {
                assetData: {
                    member: [],
                    name: ''
                },
                assetData1: {
                    member: [],
                },
                defaultProps: {
                    label: 'name',
                    value: 'id'
                },
                title: '新增盘点',
                searchForm: {},
                daterange: '',
                tableData: [],
                treeData1: [],
                viewFlag: false,
                optionsYh: [],
                optionsGly: [],
                treeDeptData: [],
                treeCateData: [],
                optionsZt: [],
                modal: false,
                modal1: false,
                inventoryId: '',
                modal2: false,
                rules: {
                    name: [
                        { required: true, message: '请输入盘点单名称' }
                    ],
                    member: [
                        { required: true, message: '请输入选择分配用户'},
                    ]
                },
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: false,
                    delBtn: this.vaildData(this.permissions.act_assetinventory_del, false),
                    editBtn: false
                };
            }
        },
        created() {
            this.init()
        },
        methods: {
            init() {
                roleCodeArray(['ROLE_SERVICE_ASSET_HANDEL']).then(response => {
                    this.optionsGly = response.data.data
                })
                roleCodeArray(['ROLE_SERVICE_ASSET_INVENTORY']).then(response => {
                    this.optionsYh = response.data.data
                })
                 // 资产状态
                remote('asset_use_status').then(response => {
                    this.optionsZt = response.data.data
                })
                fetchTree().then(response => {
                    this.treeDeptData = response.data.data
                })
                fetchTree1().then(response => {
                    this.treeCateData = response.data.data
                })
                fetchTree2().then(response => {
                    this.treeData1 = response.data.data
                })
            },
            showRecord(scope) {
                this.inventoryId = scope.row.inventoryId
                this.modal2 = true
            },
            closeDialog1() {
                this.modal = false
                this.daterange = ''
                this.assetData = {
                    member: [],
                    name: ''
                }
            },
            submit(scope) {
                this.$alert('盘盈资产自动入库，已盘资产修改内容自动更新资产信息', '提交盘点结果', {
                    confirmButtonText: '确定',
                    callback: action => {
                        if (action === 'cancel') {
                        } else {
                            submit(scope.row.inventoryId).then(response => {
                                this.$message.success('提交成功')
                                this.getList(this.page)
                            })
                        }
                    }
                });
            },
            closeDialog2() {
                this.modal1 = false
                this.assetData1 = {
                    member: [],
                }
            },
            changeStatus(value, scope) {
                let params = {
                    inventoryId: scope.row.inventoryId,
                    status: ''
                }
                if (scope.row.status == '0') {
                    params.status = '1'
                } else {
                    params.status = '0'
                }
                changeStatus(params).then(response => {
                    this.$message.success('修改成功')
                    this.getList(this.page)
                })
            },
            assignDia(scope) {
                this.inventoryId = scope.row.inventoryId
                let list = []
                scope.row.member.split(',').map(item => {
                    list.push(Number(item))
                })
                this.assetData1.member = list
                this.modal1 = true
            },
            openform(scope, type) {
                this.modal = true
                if(type) {
                    this.viewFlag = true
                    this.title = "盘点详情"
                    let att = Object.assign({}, scope.row)
                    if (att.member) {
                        let list = []
                        att.member.split(',').map(item => {
                            list.push(Number(item))
                        })
                        att.member = list
                    }
                    if (att.categoryIds) {
                        att.categoryIds = att.categoryIds.split(',')
                    }
                    if (att.assetStatus) {
                        att.assetStatus = att.assetStatus.split(',')
                    }
                    if (att.areaIds) {
                        att.areaIds = att.areaIds.split(',')
                    }
                    if (att.deptIds) {
                        att.deptIds = att.deptIds.split(',')
                    }
                    if (att.handleIds) {
                        let list1 = []
                        att.handleIds.split(',').map(item => {
                            list1.push(Number(item))
                        })
                        att.handleIds = list1
                    }
                    if (att.startDate) {
                        this.daterange = [att.startDate, att.endDate]
                    }
                    this.assetData = att
                } else {
                    this.viewFlag = false
                    this.title = "新增盘点"
                }
            },
            alarmHandle1(formName) {
                const _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let att = Object.assign({}, _this.assetData1)
                        if (_this.assetData1.member && _this.assetData1.member.length) {
                            att.member = _this.assetData1.member.join(',')
                        }
                        att.inventoryId = _this.inventoryId
                        assignMember(att).then(response => {
                            this.$message.success('分配成功')
                            this.closeDialog2()
                            this.getList(this.page)
                        })
                    }
                })
            },
            alarmHandle(formName) {
                const _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let att = Object.assign({}, _this.assetData)
                        if (_this.assetData.member && _this.assetData.member.length) {
                            att.member = _this.assetData.member.join(',')
                        } else {
                            att.member = ''
                        }
                        if (_this.assetData.deptIds && _this.assetData.deptIds.length) {
                            att.deptIds = _this.assetData.deptIds.join(',')
                        } else {
                            att.deptIds = ''
                        }
                        if (_this.assetData.categoryIds && _this.assetData.categoryIds.length) {
                            att.categoryIds = _this.assetData.categoryIds.join(',')
                        } else {
                            att.categoryIds = ''
                        }
                        if (_this.assetData.areaIds && _this.assetData.areaIds.length) {
                            att.areaIds = _this.assetData.areaIds.join(',')
                        } else {
                            att.areaIds = ''
                        }
                        if (_this.assetData.handleIds && _this.assetData.handleIds.length) {
                            att.handleIds = _this.assetData.handleIds.join(',')
                        } else {
                            att.handleIds = ''
                        }
                        if (_this.assetData.assetStatus && _this.assetData.assetStatus.length) {
                            att.assetStatus = _this.assetData.assetStatus.join(',')
                        } else {
                            att.assetStatus = ''
                        }
                        if (_this.daterange && _this.daterange.length) {
                            att.startDate = _this.daterange[0]
                            att.endDate = _this.daterange[1]
                        }
                        addObj(att).then(response => {
                            this.$message.success('添加成功')
                            this.closeDialog1()
                            this.getList(this.page)
                        })
                    }
                })
            },
            getList(page, params) {
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            rowDel: function (row, index) {
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.inventoryId)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            handleUpdate: function (row, index, done,loading) {
                putObj(row).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                addObj(row).then(data => {
                    this.$message.success('添加成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>

<style scoped lang="scss">
.asset-member-dialog{
    .el-cascader, .el-select, .el-input-number, .el-date-editor {
        width: 100%;
    }
}
.pd-dialog{
    /deep/.el-dialog__body{
        padding: 0;
    }
}
.asset-dialog{
    /deep/.el-dialog__body{
        height: 80vh;
        overflow: auto;
    }
    .el-cascader, .el-select, .el-input-number, .el-date-editor {
        width: 100%;
    }
    .block-header{
        font-size: 18px;
        color: #222;
        font-weight: bold;
        margin-bottom: 10px;
    }
    /deep/.avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    /deep/.avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }

    /deep/.avatar-uploader-icon {
        font-size: 28px !important;
        color: #8c939d !important;
        width: 178px !important;
        height: 178px !important;
        line-height: 178px !important;
        text-align: center !important;
    }

    /deep/.avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
}
</style>